<template>
  <div class="article-page">
    <nav class="my-nav van-hairline--bottom">
      <a href="javascript:;" @click="changeSorter('weight_desc')" :class="{active:page.sorter === 'weight_desc'}">推荐</a>
      <a href="javascript:;" @click="changeSorter(null)" :class="{active:page.sorter === null}">最新</a>
      <div class="logo"><img src="@/assets/logo.png" alt="" /></div>
    </nav>

    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="别刷了，没了"
      @load="onLoad"
    >
      <ArticleItems v-for="item in renderData" :key="item.id" :data="item"/>
    </van-list>

  </div>
</template>

<script>
import { getArticleList } from '@/api/article'

export default {
  name: 'article-page',
  data () {
    return {
      renderData: [],
      loading: false,
      finished: false,
      page: {
        current: 1,
        pageSize: 10,
        sorter: null
      }
    }
  },

  methods: {
    // load函数触发时机：1.组件刚加载的时候会触发一次，2.滚动条小于一定距离的时候会触发（finished为false，loading为false）
    async onLoad () {
      // 利用组件刚加载的时候会触发的特性，不需要created
      const { data } = await getArticleList(this.page.current, this.page.pageSize, this.page.sorter)

      // 将获取到的数据渲染
      this.renderData = [...this.renderData, ...data.rows]

      // 将本地的current参数加一，准备请求下一页的数据
      this.page.current += 1

      // 将loading状态关闭
      this.loading = false

      // 没数据了之后就把finished改为true，停止加载
      if (this.page.current > data.pageTotal) return (this.finished = true)
    },

    // 改变排序
    changeSorter (value) {
      this.page.sorter = value

      // 再次发起请求之前，需要把之前的数据清空
      this.renderData = []

      this.page.current = 1

      this.finished = false // finished需要打开

      this.loading = true

      this.onLoad()
    }

  }
}
</script>

<style lang="less" scoped>
.article-page {
  margin-bottom: 50px;
  margin-top: 44px;
  .my-nav {
    height: 44px;
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    z-index: 999;
    background: #fff;
    display: flex;
    align-items: center;
    > a {
      color: #999;
      font-size: 14px;
      line-height: 44px;
      margin-left: 20px;
      position: relative;
      transition: all 0.3s;
      &::after {
        content: '';
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
        bottom: 0;
        width: 0;
        height: 2px;
        background: #222;
        transition: all 0.3s;
      }
      &.active {
        color: #222;
        &::after {
          width: 14px;
        }
      }
    }
    .logo {
      flex: 1;
      display: flex;
      justify-content: flex-end;
      > img {
        width: 64px;
        height: 28px;
        display: block;
        margin-right: 10px;
      }
    }
  }
}
</style>
